package com.ruoyi.system.utils;

import com.mongodb.client.gridfs.model.GridFSFile;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * GridFS工具类
 */
public class GridFsUtils {
    
    private static final Logger log = LoggerFactory.getLogger(GridFsUtils.class);

    /**
     * 上传文件到GridFS
     */
    public static String uploadFile(GridFsTemplate gridFsTemplate, MultipartFile file) throws IOException {
        ObjectId objectId = gridFsTemplate.store(
            file.getInputStream(), 
            file.getOriginalFilename(),
            file.getContentType()
        );
        return objectId.toString();
    }

    /**
     * 从GridFS下载文件
     */
    public static GridFsResource downloadFile(GridFsTemplate gridFsTemplate, String fileId) {
        try {
            // 将字符串ID转换为ObjectId
            ObjectId objectId = new ObjectId(fileId);
            
            // 使用ObjectId查询
            Query query = Query.query(Criteria.where("_id").is(objectId));
            
            // 先查找文件是否存在
            GridFSFile gridFSFile = gridFsTemplate.findOne(query);
            if (gridFSFile == null) {
                log.error("文件不存在，fileId: {}", fileId);
                return null;
            }
            
            // 获取文件资源
            return gridFsTemplate.getResource(gridFSFile);
            
        } catch (IllegalArgumentException e) {
            log.error("无效的ObjectId格式: {}", fileId, e);
            return null;
        } catch (Exception e) {
            log.error("下载文件失败: {}", fileId, e);
            return null;
        }
    }

    /**
     * 从GridFS删除文件
     */
    public static void deleteFile(GridFsTemplate gridFsTemplate, String fileId) {
        try {
            ObjectId objectId = new ObjectId(fileId);
            gridFsTemplate.delete(Query.query(Criteria.where("_id").is(objectId)));
        } catch (IllegalArgumentException e) {
            log.error("无效的ObjectId格式: {}", fileId, e);
        } catch (Exception e) {
            log.error("删除文件失败: {}", fileId, e);
        }
    }
} 